package com.gegong.imr.client.tasks.vmware;

import com.gegong.imessage.dto.TVmTask;
import com.gegong.imr.client.IMessageClientProfiles;
import com.gegong.imr.client.bean.TaskCmd;
import com.gegong.imr.client.config.ImrCenterConfig;
import com.gegong.imr.client.config.ImrClientConfig;
import com.gegong.imr.client.tasks.AbstractProcessCommandTask;
import com.gegong.imr.client.tasks.CenterResponse;
import com.gegong.imr.client.tasks.TaskException;
import com.gegong.imr.client.utils.os.MachineUtils;
import com.gegong.vmware.workstation.CopyVmRequestParameter;
import com.gegong.vmware.workstation.VMInformation;
import com.gegong.vmware.workstation.exceptions.VMwareWorkstationManagementException;
import com.gegong.vmware.workstation.service.VMManagementService;
import com.gegong.vmware.workstation.service.VMNetworkAdaptersManagementService;
import com.gegong.vmware.workstation.service.VMPowerManagementService;
import com.gegong.vmware.workstation.utils.VMMacAddressUtils;
import com.google.common.collect.ImmutableMap;
import javafx.application.Platform;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
@Slf4j
@Profile(IMessageClientProfiles.VMWARE)
public class VmwareProcessCommandTask extends AbstractProcessCommandTask {

    private final VMManagementService managementService;
    private final VMPowerManagementService powerManagementService;
    private VMNetworkAdaptersManagementService networkAdaptersManagementService;
    private final ImrClientConfig clientConfig;

    @Autowired
    public VmwareProcessCommandTask(VMManagementService managementService,
                                    VMPowerManagementService powerManagementService,
                                    ImrCenterConfig imrCenterConfig,
                                    ImrClientConfig clientConfig,
                                    VMNetworkAdaptersManagementService networkAdaptersManagementService) {
        super(imrCenterConfig);
        this.managementService = managementService;
        this.powerManagementService = powerManagementService;
        this.clientConfig = clientConfig;
        this.networkAdaptersManagementService = networkAdaptersManagementService;
    }

    @Override
    public void run() {
        log.info("从服务器查询任务...");
        TVmTask machineTask = null;
        try {
            machineTask = queryTask(ImmutableMap.<String, Object>builder()
                    .put("client_code", MachineUtils.getCPUSerialNumber())
                    .put("virtual_num", managementService.findAll().size())
                    .build());
        } catch (TaskException | VMwareWorkstationManagementException e) {
            log.error(e.getMessage(), e);
        }

        if (Objects.nonNull(machineTask)) {

            try {
                log.info("正在执行任务..." + machineTask);
                switch (TaskCmd.fromValue(machineTask.getTaskCmd())) {
                    case copy_virtual:
                    case modify_virtual:
                        VMInformation vm = managementService.copyVm(CopyVmRequestParameter.builder()
                                .parentId(getVmId(clientConfig.getTemplateVmName()))
                                .newVmName(machineTask.getVirtualName()).build());
                        log.info("虚拟机{}复制完成", vm.toString());
                        String newMac = VMMacAddressUtils.addSplitter(machineTask.getVirtualMac(), ":");
                        log.info("设置虚拟机{}的MAC地址为{}", managementService.getVmNameById(vm.getId()), newMac);
                        networkAdaptersManagementService.setMacAddress(vm.getId(), 0, newMac);
                        log.info("设置MAC地址完成");
                        break;
                    case start_virtual:
                        log.info(powerManagementService.powerOn(getVmId(machineTask.getVirtualName())).toString());
                        break;
                    case shutdown_virtual:
                        log.info(powerManagementService.shutdown(getVmId(machineTask.getVirtualName())).toString());
                        break;
                    case restart_virtual:
                        log.info(powerManagementService.restart(getVmId(machineTask.getVirtualName())).toString());
                        break;
                    case del_virtual:
                        managementService.deleteVm(getVmId(machineTask.getVirtualName()));
                        break;
                    default:
                        throw new UnsupportedOperationException("不支持的命令");
                }


            } catch (Throwable e) {
                code = 0;
                message = e.getMessage();
                log.error(e.getMessage(), e);
            } finally {
                try {
                    reportExecutedStatus(machineTask.getTaskId(), code, message);
                } catch (TaskException e) {
                    log.error(e.getMessage(), e);
                }
            }

        }

    }

    private String getVmId(String vmName) throws VMwareWorkstationManagementException {
        return managementService.findByName(vmName).getId();
    }
}
